<?php

declare(strict_types=1);

namespace app\admin\middleware;

use app\admin\service\interface\CacheService;
use think\facade\Cache;
use think\facade\Event;
use think\Request;

class CheckCache
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //初始化缓存
        if (!Cache::has(CacheService::CACHE_CONFIG)) {
            invoke(function (CacheService $cacheService) {
                $cacheService->init();
            });
        }
        $GLOBALS["nav"] = Cache::get(CacheService::CACHE_NAV);
        $GLOBALS["config"] = Cache::get(CacheService::CACHE_CONFIG);
        // Event::listen('RouteLoaded', function(Request $param) {
        //     // var_dump($param->pathinfo());
        // });
        $GLOBALS["crumbs"] = $this->buildCrumbs($request->pathinfo());
        return $next($request);
    }
    public function buildCrumbs(string $pathinfo)
    {
        $res = [];
        $nav = $GLOBALS['nav'];
        $navs_by_path = $nav['navs_by_path'];
        $navs_by_id = $nav['navs_by_id'];
        $res['module'] = empty($GLOBALS["config"]['admin']) ? 'admin' : $GLOBALS["config"]['admin'];
        $res['controller'] = 'index';
        $res['action'] = 'index';
        if (!empty($pathinfo)) {
            if (str_contains($pathinfo, '.')) {
                $pathinfo = explode('.', $pathinfo)[0];
            }
            $arr = explode('/', $pathinfo);
            if (count($arr) == 1 && !empty($arr[0])) {
                $res['controller'] = $arr[0];
            } elseif (count($arr) == 2) {
                $res['controller'] = $arr[0];
                if (!empty($arr[1])) {
                    $res['action'] = $arr[1];
                }
            } else {
                $res['controller'] = $arr[0];
                $res['action'] = $arr[1];
            }
        }
        $res['path'] = "{$res['module']}/{$res['controller']}/{$res['action']}";
        $res['items'] = [];
        $res['nav_group_id'] = 0;
        $res['nav_item_id'] = 0;
        if(!array_key_exists($res['path'], $navs_by_path)) {
           return $res; 
        }
        $item = $navs_by_path[$res['path']];
        $res['nav_group_id'] = $item['group_id'];
        $res['nav_item_id'] = $item['id'];
        $res['items'][] = $item;
        while ($item['pre_id'] > 0) {
            if(!array_key_exists($item['pre_id'], $navs_by_id)) {
                break;
             }
            $item = $navs_by_id[$item['pre_id']];
            if (!empty($item)) {
                $res['items'][] = $item;
            }
        }
        $res['items'] = array_reverse($res['items']);
        return $res;
    }
}
